<template>
  <div class="divBox">
    <el-card class="box-card">
      <div class="clearfix">
        <div class="container">
          <el-form inline size="small">
            <el-form-item label="关键字">
              <el-input
                v-model.trim="listPram.keywords"
                placeholder="请输入id，名称，描述"
                clearable
                class="selWidth"
                size="small"
              >
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button size="small" type="primary" @click="handlerSearch"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <el-button size="small" type="primary" @click="handlerEditData(null, 0)"
          >创建表单
        </el-button>
      </div>
      <el-table
        :data="dataList.list"
        size="small"
        class="table"
        @current-change="handleCurrentRowChange"
        :header-cell-style="{ fontWeight: 'bold' }"
      >
        <el-table-column label="ID" prop="id" width="80" />
        <el-table-column label="名称" prop="name" min-width="180" />
        <el-table-column label="描述" prop="info" min-width="220" />
        <el-table-column label="状态" prop="status" min-width="80">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="true"
              :inactive-value="false"
              @change="handlerSwitch(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" prop="updateTime" min-width="200">
          <template #default="scope">
            {{ scope.row.updateTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click="handlerEditData(scope.row.id, 1)"
              >编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="handlerDelete(scope.row)"
              >删除
            </el-button>
            <el-button
              type="text"
              size="small"
              id="copyUrlNode"
              @click="saveCurrentItemId(scope.row)"
            >
              链接
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="getUserSubmitData(scope.row)"
            >
              收集
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="listPram.page"
        :page-sizes="[10, 20, 30, 40]"
        :total="dataList.total"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      v-model="editDialogConfig.visible"
      fullscreen
      :title="editDialogConfig.isCreate === 0 ? '创建表单' : '编辑表单'"
      destroy-on-close
      :close-on-click-modal="false"
      :before-close="handlerHide"
    >
      <Designer
        v-if="editDialogConfig.visible"
        :is-create="editDialogConfig.isCreate"
        :id="editDialogConfig.id"
      />
    </el-dialog>
    <el-drawer direction="ltr" v-model="drawer" size="80%">
      <template #default>
        <el-table :data="userCollect">
          <el-table-column
            :label="item.label"
            :prop="item.prop"
            v-for="(item, index) in columnPropCollect"
            :key="index"
          />
        </el-table>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import {
  deleteFormTempApi,
  getFormTempInfo,
  getFormTempList,
  getSubmitUserList,
  switchFormTempStatus
} from '@/request/formTemp'
import Designer from '@/views/design/Designer.vue'
import {
  defineEmits,
  defineProps,
  onBeforeUnmount,
  onMounted,
  reactive,
  ref
} from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import ClipboardJS from 'clipboard'
import { formConfigInfo } from '@/request/formConfig'
import { deepClone } from '@/utils'

const emit = defineEmits(['selectedRowData'])
const listPram = reactive({
  keywords: null,
  page: 1,
  limit: 10
})
const editDialogConfig = reactive({
  visible: false,
  id: null,
  isCreate: 0
})
const dataList = reactive({ list: [], total: 0 })
const selectedConfigData = ref({})
var clipboard = reactive(null)
const drawer = ref(false)
const currentItemId = ref(0)
const userCollect = ref([])
const columnPropCollect = ref([])
const handlerSearch = function () {
  listPram.page = 1
  handlerGetList(listPram)
}
const handlerGetList = function (pram) {
  pram.userId = localStorage.getItem('userId')
  getFormTempList(pram).then((response) => {
    let { data } = response
    dataList.list = data.list
    dataList.total = parseInt(data.total)
  })
}
const handlerEditData = function (id, isCreate) {
  editDialogConfig.id = id
  editDialogConfig.isCreate = isCreate
  editDialogConfig.visible = true
}

const handlerDelete = function (rowData) {
  let { id } = rowData
  ElMessageBox.confirm(`你确定要删除表单Id为${id}吗?`, '🗑️删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      let userId = localStorage.getItem('userId')
      deleteFormTempApi({ id: rowData.id, userId: userId })
        .then((resp) => {
          console.log(resp)
          let { code, msg } = resp
          if (code === 200) {
            ElMessage({
              type: 'success',
              message: msg
            })
          } else {
            ElMessage({
              type: 'error',
              message: msg
            })
          }
        })
        .catch((reason) => {
          ElMessage({
            type: 'error',
            message: reason
          })
        })
    })
    .catch(() => {})
}
const saveCurrentItemId = function (rowData) {
  let { id } = rowData
  currentItemId.value = id
}
const getUserSubmitData = async function (rowData) {
  userCollect.value = []
  columnPropCollect.value = []
  let { id } = rowData
  let resp = await getSubmitUserList({ formId: id })
  let { data } = resp
  let hasNotColumn = true
  columnPropCollect.value.push(
    {
      prop: 'userId',
      label: '用户Id'
    },
    {
      prop: 'nickName',
      label: '账号'
    },
    {
      prop: 'userName',
      label: '用户名'
    }
  )
  let tempUserData = {}
  let formTempResponse = await getFormTempInfo({ id: id })
  let { content } = formTempResponse.data
  let itemList = JSON.parse(content, null)
  for (let formTempItem of itemList) {
    tempUserData[formTempItem['__config__']['itemName']] = null
    if (hasNotColumn) {
      columnPropCollect.value.push({
        label: formTempItem['__config__']['label'],
        prop: formTempItem['__config__']['itemName']
      })
    }
  }
  for (let userItem of data) {
    tempUserData['userId'] = userItem['userId']
    tempUserData['nickName'] = userItem['nickName']
    tempUserData['userName'] = userItem['userName']

    let formConfigResponse = await formConfigInfo({
      id: id,
      userId: userItem['userId']
    })
    let formConfigList = formConfigResponse.data
    for (let formConfigItem in formConfigList) {
      tempUserData[formConfigItem] = convertToNumber(
        formConfigList[formConfigItem]
      )
    }
    userCollect.value.push(deepClone(tempUserData))
  }

  drawer.value = true

  if (hasNotColumn) {
    hasNotColumn = false
  }
}
function convertToNumber(str) {
  if (typeof str === 'string') {
    const num = parseFloat(str)
    if (!isNaN(num)) {
      if (num.toString() === str) {
        return num
      }
      return str
    }
  }
  return str
}
const handlerHide = function () {
  editDialogConfig.id = null
  editDialogConfig.isCreate = 0
  editDialogConfig.visible = false
  handlerGetList(listPram)
}
const handleSizeChange = function (val) {
  listPram.limit = val
  handlerGetList(listPram)
}
const handleCurrentChange = function (val) {
  listPram.page = val
  handlerGetList(listPram)
}
const handleCurrentRowChange = function (rowData) {
  selectedConfigData.value = rowData
}
const handlerConfimSelect = function () {
  emit('selectedConfigData', selectedConfigData)
}

const getShareUrl = function () {
  let baseUrl = window.document.location.origin
  let id = currentItemId.value
  return `${baseUrl}/render/${id}`
}
const handlerSwitch = function (rowData) {
  let { id, status } = rowData
  let userId = localStorage.getItem('userId')
  switchFormTempStatus({
    id: id,
    userId: userId,
    status: status
  })
    .then((resp) => {
      let { code } = resp
      if (code === 200) {
        ElMessage({
          type: 'success',
          message: '变更成功'
        })
      } else {
        ElMessage({
          type: 'error',
          message: '变更失败'
        })
      }
    })
    .catch((reason) => {
      ElMessage({
        type: 'error',
        message: reason
      })
    })
}
onMounted(() => {
  handlerGetList(listPram)

  clipboard = new ClipboardJS('#copyUrlNode', {
    // eslint-disable-next-line no-unused-vars
    text: (trigger) => {
      const codeStr = getShareUrl()
      ElNotification({
        title: '成功',
        message: '任务链接已复制到剪切板，请尽快分享给好友吧。',
        type: 'success'
      })
      return codeStr
    }
  })
  // eslint-disable-next-line no-unused-vars
  clipboard.on('error', (e) => {
    ElMessage.error('任务链接复制失败')
  })
})
onBeforeUnmount(() => {
  clipboard && clipboard.destroy()
})
</script>
<style scoped lang="scss">
.divBox {
  padding: 20px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

.box-card {
  height: 320px;
}

.clearfix {
  &:after {
    visibility: hidden;
    display: block;
    font-size: 0;
    content: ' ';
    clear: both;
    height: 0;
  }
}

.table {
  .el-image {
    width: auto !important;
    height: 30px !important;
  }

  .el-image__placeholder,
  .el-image__error {
    width: auto !important;
  }
}

.selWidth {
  width: 250px !important;
}

.container {
  min-width: 821px;
}

.selWidth {
  width: 100%;
}
</style>
